package com.accloud.cloudservice;

import com.accloud.service.ACException;
import com.accloud.utils.AesUtil;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;

/* access modifiers changed from: package-private */
public class SecuritySession {
    public static final byte SECURITY_TYPE_AES = 2;
    public static final byte SECURITY_TYPE_NONE = 0;
    public static final byte SECURITY_TYPE_RSA = 1;
    private String aesKey;
    private final byte resver = 0;
    private final byte secType;

    public SecuritySession(String aesKey2) {
        byte b = 0;
        this.secType = aesKey2 != null ? 2 : b;
        this.aesKey = aesKey2;
    }

    public byte[] encrypt(LocalMessage localMessage) throws GeneralSecurityException {
        byte[] encrypted;
        byte[] content = localMessage.toBytes();
        if (this.aesKey != null) {
            encrypted = AesUtil.encrypt(content, this.aesKey.getBytes());
        } else {
            encrypted = content;
        }
        return ByteBuffer.allocate(encrypted.length + 4).putShort((short) encrypted.length).put(this.secType).put((byte) 0).put(encrypted).array();
    }

    public LocalMessage decrypt(byte[] bytes) throws GeneralSecurityException, ACException {
        return decrypt(bytes, this.aesKey);
    }

    public static LocalMessage decrypt(byte[] bytes, String aesKey2) throws GeneralSecurityException, ACException {
        byte[] content;
        int length = ByteBuffer.wrap(bytes).getShort() & 65535;
        byte[] encrypted = ByteBuffer.allocate(length).put(bytes, 4, length).array();
        if (aesKey2 != null) {
            content = AesUtil.decrypt(encrypted, aesKey2.getBytes());
        } else {
            content = encrypted;
        }
        return LocalMessage.fromBytes(content);
    }

    public LocalMessage decrypt(InputStream inputStream) throws ACException, GeneralSecurityException, IOException {
        byte[] content;
        ByteBuffer securityHead = ByteBuffer.allocate(4);
        inputStream.read(securityHead.array());
        byte[] encrypted = new byte[(securityHead.getShort() & 65535)];
        inputStream.read(encrypted);
        if (this.aesKey != null) {
            content = AesUtil.decrypt(encrypted, this.aesKey.getBytes());
        } else {
            content = encrypted;
        }
        return LocalMessage.fromBytes(content);
    }
}
